package util;

import java.util.Vector;

import ns2.Connection;
import ns2.Field;

public class Connections extends Vector<Connection> {

	private static final long serialVersionUID = 1L;

	public void addConnection(Connection connection) {
		if (!this.exist(connection)) {
			this.addElement(connection);
		}
	}

	public void addAll(Connections connections) {
		for (int i = 0; i < connections.size(); i++) {
			this.addConnection(connections.elementAt(i));
		}
	}

	public boolean exist(Connection connection) {
		boolean exist = false;
		int index = 0;
		while (!exist && index < this.size()) {
			exist = connection.equals(this.elementAt(index));
			index++;
		}
		return exist;
	}

	public Vector<Connections> sort(Field field) {
		Vector<Connections> results = new Vector<Connections>();
		Vector<Integer> reference = new Vector<Integer>();
		Integer nodeID = new Integer(65535);
		for (int i = 0; i < this.size(); i++) {
			switch (field) {
			case Src_addr:
				nodeID = new Integer(this.elementAt(i).getSrc());
				break;
			case Dst_addr:
				nodeID = new Integer(this.elementAt(i).getDst());
				break;
			default:
				break;
			}
			if ((nodeID.intValue() != 65535) && (!reference.contains(nodeID))) {
				reference.addElement(nodeID);
				results.addElement(new Connections());
			}
			int index = reference.indexOf(nodeID);
			results.elementAt(index).addConnection(this.elementAt(i));
		}
		results.trimToSize();
		for (int i = 0; i < results.size(); i++) {
			results.elementAt(i).trimToSize();
		}
		return results;
	}

	public void compact() {
		this.trimToSize();
	}

}
